﻿using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 2021/12/25 0:15:40  LazyCoder
/// 
/// </summary>
namespace SH.Ms.JwtHelper
{
    /// <summary>
    /// Jwt 通过模型获取 Claims 
    /// @作者:LazyCoder
    /// @日期:2021年12月27日
    /// </summary>
    public static class JwtHelpers
    {

        public static IEnumerable<Claim> GetClaims(this UserTokens userAccounts)
        {
         
            List<Claim> claims = new List<Claim>  {
                new Claim(ClaimTypes.Role,userAccounts.Roles),
                new Claim("Id", userAccounts.Id.ToString()),
                new Claim(ClaimTypes.Name, userAccounts.UserName??""),
                new Claim(ClaimTypes.Email, userAccounts.EmailId??""),
                new Claim(ClaimTypes.NameIdentifier, userAccounts.Id.ToString()),
                new Claim(ClaimTypes.Expired,userAccounts.ExpiredTime.ToString("F"))
            };
            claims.AddRange(userAccounts.ClaimsExt.Select(t => new Claim(t.Key, t.Value)));
            return claims;
        }

        public static UserTokens GenTokenkey(UserTokens model, JwtSettings jwtSettings)
        {
            try
            {
               
                if (model == null) throw new ArgumentException(nameof(model));
                // Get secret key
                var key = System.Text.Encoding.ASCII.GetBytes(jwtSettings.IssuerSigningKey);
                var JWToken = new JwtSecurityToken(issuer: jwtSettings.ValidIssuer,
                    audience: jwtSettings.ValidAudience, 
                    claims: GetClaims(model), 
                    notBefore: new DateTimeOffset(DateTime.Now).DateTime,
                    expires: new DateTimeOffset(model.ExpiredTime).DateTime, 
                    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256));
                model.Token = new JwtSecurityTokenHandler().WriteToken(JWToken);
                return model;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
